<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8" />
    <title>文档查重</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            padding: 40px;
            background-color: #f5f5f5;
        }
        .container {
            max-width: 800px;
            margin: auto;
        }
        textarea {
            width: 100%;
            height: 300px;
            padding: 10px;
            font-size: 16px;
            border-radius: 8px;
            border: 1px solid #ccc;
            resize: vertical;
        }
        select, button {
            margin-top: 10px;
            padding: 10px;
            font-size: 16px;
        }
        .result {
            margin-top: 30px;
            background: white;
            padding: 20px;
            border-radius: 8px;
        }
        .result-item {
            margin-bottom: 40px;
            border-top: 1px solid #ddd;
            padding-top: 15px;
            background-color: #fff;
            box-shadow: 0 2px 6px rgba(0,0,0,0.05);
            border-radius: 8px;
            padding: 15px;
        }
    </style>
</head>
<body>

<div class="container">
    <div style="display: flex; align-items: center; justify-content: space-between; margin-bottom: 20px;">
        <!-- 返回按钮 -->
        <a href="/"><button style="padding: 8px 16px; font-size: 16px; background-color: #6c757d; color: white; border: none; border-radius: 4px; cursor: pointer;">← 返回首页</button></a>

        <!-- 居中的标题 -->
        <h2 style="flex: 1; text-align: center; margin: 0;">文档查重</h2>

        <!-- 右侧占位，保持布局对称 -->
        <div style="width: 100px;"></div>
    </div>
    <textarea id="userText" placeholder="请粘贴或输入要查重的文本..."></textarea>
    <br/>
    <select id="langSelect">
        <option value="cn">中文</option>
        <option value="en">英文</option>
    </select>
    <button onclick="checkDuplicates()">开始查重</button>

    <div id="results" class="result" style="display:none;"></div>
</div>

<script>
function checkDuplicates() {
    const text = document.getElementById("userText").value.trim();
    const lang = document.getElementById("langSelect").value;

    if (!text) {
        alert("请输入文本内容");
        return;
    }

    const userTokens = [...new Set(text.split(/[\s\W]+/).filter(Boolean))];

    fetch(`/api/duplicate-check?lang=${lang}`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ text })
    })
    .then(res => res.json())
    .then(data => {
        if (data.error) {
            alert(data.error);
            return;
        }

        const resultsDiv = document.getElementById("results");
        resultsDiv.innerHTML = "<h3>查重结果（相似度 Top 10）:</h3>";

        if (!data.results.length) {
            resultsDiv.innerHTML += "<p>未找到相似文档</p>";
        } else {
            // 显示查重率
            if (data.plagiarism_rate !== undefined) {
                const rate = (data.plagiarism_rate * 100).toFixed(2);
                resultsDiv.innerHTML += `<p>⚠️ 文档查重率: <strong>${rate}%</strong></p>`;
            }

            // 获取用户输入的关键词
            const userWords = data.user_tokens || [];

            // 构建高亮正则表达式
            function escapeRegExp(string) {
                return string.replace(/[.*+?^${}()|[$$\\]/g, '\\$&');
            }
            const pattern = new RegExp(`(${userWords.map(w => escapeRegExp(w)).join('|')})`, 'gi');

            function highlightText(text) {
                // 去除每行开头的空白，但保留段落结构
                const cleanedText = text
                    .split('\n')                          // 按行拆分
                    .map(line => line.replace(/^\s+/, ''))// 去除每行开头空格
                    .join('\n');                         // 重新连接成字符串

                return cleanedText.replace(pattern, match => `<strong>${match}</strong>`);
            }


            // 创建占位容器
            data.results.forEach((item, index) => {
                resultsDiv.innerHTML += `
                    <div id="doc-${item.doc_id}" class="result-item"></div>
                `;
            });

            // 依次加载并插入内容
            data.results.forEach((item, index) => {
                const sim = (item.similarity * 100).toFixed(2);
                const container = document.getElementById(`doc-${item.doc_id}`);

                fetch(`/api/original-document?id=${item.doc_id}`)
                    .then(res => res.json())
                    .then(doc => {
                        let originalContent = doc.content || "[无内容]";
                        let highlightedContent = highlightText(originalContent);

                        container.innerHTML = `
                            <a href="/details?id=${item.doc_id}" target="_blank"><strong>${item.title}</strong></a><br/>
                            相似度: ${sim}%<br/>
                            <hr/>
                            <div style="font-size:14px; line-height:1.6; white-space: pre-line; word-break: break-all;">
                                ${highlightedContent}
                            </div>
                        `;
                    });
            });
        }

        resultsDiv.style.display = "block";
    })
    .catch(err => {
        console.error(err);
        alert("请求失败，请重试。");
    });
}
</script>


</body>
</html>
